package com.jdk.learn.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * package com.jdk.learn.thread;
 * <p>
 * public class SynRecompileDemo implements Runnable {
 * private volatile Integer ticket = new Integer(200);
 * <p>
 * public SynRecompileDemo() {
 * }
 * <p>
 * public void run2() {
 * Integer var1 = this.ticket;
 * synchronized(this.ticket) {
 * for(int i = 0; i < 200; ++i) {
 * if (this.ticket > 0) {
 * Integer var3 = this.ticket;
 * Integer var4 = this.ticket = this.ticket - 1;
 * }
 * }
 * <p>
 * }
 * }
 * <p>
 * public void run() {
 * synchronized(this) {
 * for(int i = 0; i < 200; ++i) {
 * if (this.ticket > 0) {
 * Integer var3 = this.ticket;
 * Integer var4 = this.ticket = this.ticket - 1;
 * }
 * }
 * <p>
 * }
 * }
 * }
 *
 *
 * cmd命令行执行：javap -verbose SynRecompileDemo.class >>SynRecompile.txt
 *
 *
 */
public class SynRecompileDemo implements Runnable {
    private volatile Integer ticket = new Integer(300);
//    public static final    Integer ticket = 200;
//    private Lock lock = new ReentrantLock();

    /**
     *  syn是悲观锁  lock是乐观锁
     *  3个线程ABC  首先竞争ticket资源
     *          假定A持有ticket锁 200
     *             A Sleep ---》BC竞争200  但是A持有中
     *             A sleep结束---》ABC同事竞争  但是A持有 200锁 继续获得执行权
     *             A 执行tickect-- 更新锁为199
     *
     *             然后循环执行。。。
     */
    @Override
    public void run() {
//        synchronized (this) {
        synchronized (ticket) {
                System.out.println("-----name:"+Thread.currentThread().getName()+"获取到锁."+ticket);
            for (int i = 0; i < 10; i++) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(5);//sleep会放弃cpu使用权 然后大家依次竞争cpu的使用权  但是持有当前锁ticket的值
                        ticket--;//如果改完后进行等待  则三个线程交替执行  乱序 因为值已经发生变量  且各线程知悉  这时候锁的对象不一致了。
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                System.out.println("name:"+Thread.currentThread().getName());
                } else {
                    break;
                }
            }
        }
    }

//    @Override
    public void run2() {
        synchronized (this) {
            for (int i = 0; i < 200; i++) {
//                if (ticket>0) {
//            ticket--;
            System.out.println("name:"+Thread.currentThread().getName());
//                }
            }
        }
    }

//    public void run3() {
//
//        try {
//            lock.lock();
//            ticket--;
//        } finally {
//            lock.unlock();
//        }
//    }

    public static void main(String[] args) throws InterruptedException {
        SynRecompileDemo sd=new SynRecompileDemo();
        new Thread(sd).start();
        Thread.sleep(5);
        new Thread(sd).start();
        Thread.sleep(5);
        new Thread(sd).start();
    }
}
